//
//  ChargingCaseViewModel.swift
//  EasePods
//
//  Created by 易先生 on 2024/5/7.
//

import UIKit
import EarbudsCommon
import CRPEarPhone
import Alamofire


public class ChargingCaseViewModel: ViewModel {

    public var itemsRelay = BehaviorRelay<[ChargingCaseCellViewModel]>(value: [])
    
    public var timeFormatDatas: [String] = []
    
    public var languageDatas: [String] = []

    private var languages: [LangsModel] = []
    
    public var lockScreenDatas: [Int] = [5,10,15,20,30]
    
    public var timeFormatIndex: Int = 0
    
    public var autoLockTimeIndex: Int = 0

    public var currentLanguageIndex: Int = 0
        
    private var supportLanguages: [Int] = []
    
    override init() {
        super.init()
        
        let hourItems: [TimeFormatCellType] = [.hours24, .hours12]
        timeFormatDatas = hourItems.map({$0.content})
        DispatchQueue.global().async {
            self.getLanguageConfig()
        }
    }
    
    func getChargingCaseItems() {
        
        var items: [ChargingCaseCellViewModel] = []
        
        let timeFormatCellModel = ChargingCaseCellViewModel(cellType: .timeFormat)
        let timeFormatString = Date.is24HourFormat ? getTimeFormatNameString(timeFormatType: .hours24) : getTimeFormatNameString(timeFormatType: .hours12)
        timeFormatCellModel.contentRelay.accept(timeFormatString)

        BluetoothManager.shared.queryTimeformat().subscribe(onNext: { [weak self] index in
            guard let self = self else { return }
            self.timeFormatIndex = index == 1 ? 0 : 1
            let timeFormatString = index == 1 ? getTimeFormatNameString(timeFormatType: .hours24) : getTimeFormatNameString(timeFormatType: .hours12)
            timeFormatCellModel.contentRelay.accept(timeFormatString)
        }).disposed(by: rx.disposeBag)
        
        items.append(timeFormatCellModel)
        
        
        let earCaseLanguageCellModel = ChargingCaseCellViewModel(cellType: .earCaseLanguage)
        BluetoothManager.shared.receiveLanguageConfig.asObservable().filterNil().subscribe(onNext: { [weak self] languageConfigModel in
            guard let self = self else { return }
            
            let allLanguages = getLanguages()
            self.languages = allLanguages.filter({languageConfigModel.supportLanguages.contains($0.cmd)})
            self.languageDatas = self.languages.map({$0.text})
            if let index = languages.firstIndex(where: {$0.cmd == languageConfigModel.currentLanguage}) {
                self.currentLanguageIndex = index
                let model = languages[index]
                earCaseLanguageCellModel.contentRelay.accept(model.text)
            }
        }).disposed(by: rx.disposeBag)
        BluetoothManager.shared.queryDeviceLanguage()
        items.append(earCaseLanguageCellModel)


        let lockScreenCellModel = ChargingCaseCellViewModel(cellType: .lockScreen)
        BluetoothManager.shared.receiveAutoLockTime.asObservable().filterNil().subscribe(onNext: { [weak self] time in
            guard let self = self else { return }
            if let index = lockScreenDatas.firstIndex(where: {$0 == time}) {
                self.autoLockTimeIndex = index
                lockScreenCellModel.contentRelay.accept("\(time)")
            }
        }).disposed(by: rx.disposeBag)
        BluetoothManager.shared.queryAutoLockTime()
        
        items.append(lockScreenCellModel)
        
        items.append(ChargingCaseCellViewModel(cellType: .notification))
        items.append(ChargingCaseCellViewModel(cellType: .contacts))

        itemsRelay.accept(items)
    }
    
    private func getTimeFormatNameString(timeFormatType: TimeFormatCellType) -> String {
        return timeFormatType.content
    }
    
    private func getLanguageConfig(){
        //网络请求为String
        AF.request(languageConfigAPI).responseString { [weak self] response in
            guard let self = self else { return }
            switch response.result {
            case .success(let encryptString):
                self.jsonToModel(dataString: encryptString)
            case .failure(let error):
                log.debug("language config fail \(error.localizedDescription)")
                self.parseLocalLanguageJsonData()
            }
        }
    }
    
    private func parseLocalLanguageJsonData(){
        if let jsonPath = Bundle.main.path(forResource: "LanguagesConfig", ofType: "json") {
            do {
                let dataString = try String(contentsOfFile: jsonPath, encoding: .utf8)
                UserDefaults.standard.set(dataString, forKey: "BAND_LANGS")
            } catch {
                log.debug("LanguagesConfig Path error")
            }
        }
    }
    
    private func jsonToModel(dataString: String) {
        //解析3DES格式的JSON文件
        if let decrypt = dataString.threeDESEncryptOrDecrypt(op: 0) {
            if let jsonData = decrypt.data(using: .utf8) {
                let decoder = JSONDecoder()
                do {
                    let langsModel = try decoder.decode(LanguageModel.self, from: jsonData)
                    saveLanguageData(langsModel.langs)
                } catch {
                    log.debug("Error decoding JSON: \(error)")
                }
            }
        }
    }
    
    /// 获取语言数据
    /// - Returns: 语言数组
    private func getLanguages() -> [LangsModel] {
        if let data = UserDefaults.standard.value(forKey: "BAND_LANGS") as? Data {
            let decoder = JSONDecoder()
            do {
                let langs = try decoder.decode([LangsModel].self, from: data)
                return langs
            } catch {
                log.debug("Error decoding JSON: \(error)")
            }
        }
        return []
    }
    
    private func saveLanguageData(_ langs: [LangsModel]){
        
        let encoder = JSONEncoder()
        do {
            let data = try encoder.encode(langs)
            UserDefaults.standard.set(data, forKey: "BAND_LANGS")
        } catch {
            print("Failed to encode langs: \(error)")
        }
    }
    
    
    public func updateTimeFormat(selectIndex: Int, indexPath: IndexPath) {
        self.timeFormatIndex = selectIndex
        let timeFormat = timeFormatDatas[selectIndex]
        let cellModel = itemsRelay.value[indexPath.row]
        cellModel.contentRelay.accept(timeFormat)
        BluetoothManager.shared.sendTimeFormat(selectIndex == 1 ? 0 : 1)

    }
    
    public func updateEarCaseLanguage(selectIndex: Int, indexPath: IndexPath) {
        
        let language = languageDatas[selectIndex]
        let cellModel = itemsRelay.value[indexPath.row]
        cellModel.contentRelay.accept(language)
        
        if selectIndex < languages.count {
            self.currentLanguageIndex = selectIndex
            let model = languages[selectIndex]
            BluetoothManager.shared.sendDeviceLanguage(language: model.cmd)
        }
    }
    
    public func updateLockScreenTime(selectIndex: Int, indexPath: IndexPath) {
        
        self.autoLockTimeIndex = selectIndex
        let time = lockScreenDatas[selectIndex]
        let cellModel = itemsRelay.value[indexPath.row]
        BluetoothManager.shared.sendAutoLockTime(time: time)
        cellModel.contentRelay.accept("\(time)")
    }
    
}
